package comgame.scenes;

import com.almasb.fxgl.app.scene.FXGLScene;
import com.almasb.fxgl.audio.AudioPlayer;
import com.almasb.fxgl.audio.Sound;
import com.almasb.fxgl.cutscene.Cutscene;
import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.Entity;
import com.almasb.fxgl.input.UserAction;
import comgame.entities.Player;
import comgame.components.AttributeComponent;
import javafx.animation.FadeTransition;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.util.Duration;

import java.net.URL;
import java.util.List;
import java.util.Objects;


public class GameScene extends FXGLScene {
    private StackPane sceneRoot;
    // 静态保存玩家实体和Player对象
    public static Entity playerEntity;
    public static Player player;
    private VBox playerInfoPanel; // 玩家属性面板
    private javafx.animation.Timeline infoPanelTimeline;
    private javafx.scene.control.Label moneyLabel;

    public GameScene() {
        
        boolean isFirstCreation = false;
        
        // 只在第一次创建playerEntity和player
        if (playerEntity == null) {
            playerEntity = FXGL.spawn("player", 200, 400);
            player = new Player(playerEntity);
            isFirstCreation = true;
            
            // 立即隐藏player实体，避免创建时的闪烁
            playerEntity.getViewComponent().setVisible(false);
            
            // 移除了延迟显示逻辑，让各个场景自己管理player实体的可见性
        } else if (!playerEntity.isActive()) {
            // 如果playerEntity不在活动状态，重新添加到世界
            FXGL.getGameWorld().addEntity(playerEntity);
        }
        
        // 检查player实体的可见性状态（只在非首次创建时）
        if (playerEntity != null && player != null && !isFirstCreation) {
            // 如果玩家实体存在且活跃，在GameScene中应该是可见的
            if (playerEntity.isActive()) {
                playerEntity.getViewComponent().setVisible(true);
            } else {
                // 如果玩家实体不活跃，重新创建
                recreatePlayerEntity();
            }
        }
        
        // 只在首次创建时从存档加载数据，避免覆盖内存中的最新数据
        if (isFirstCreation) {
            org.json.JSONObject saveObj = comgame.scenes.DataSaveManager.getLastPlayerSaveObj();
            if (saveObj != null) {
                player.getMoneyComponent().setAmount(saveObj.getInt("money"));
                player.getSkillComponent().setCombatLevel(saveObj.getInt("combatLevel"));
                player.getSkillComponent().setCombatExp(saveObj.getInt("combatExp"));
                player.getSkillComponent().setFarming(saveObj.getInt("farmingLevel"));
                
                // 设置血量
                int maxHealth = saveObj.getInt("maxHealth");
                player.setMaxHealth(maxHealth);
                // 确保当前血量等于最大血量
                if (player.getHealthComponent() != null) {
                    player.getHealthComponent().setHealth(maxHealth);
                }
                
                // 加载装备
                String swordName = saveObj.optString("sword", "");
                String helmetName = saveObj.optString("helmet", "");
                String chestplateName = saveObj.optString("chestplate", "");
                String leggingName = saveObj.optString("legging", "");
                String bootName = saveObj.optString("boot", "");
                
                if (!swordName.isEmpty()) {
                    player.equipByName(swordName);
                }
                if (!helmetName.isEmpty()) {
                    player.equipByName(helmetName);
                }
                if (!chestplateName.isEmpty()) {
                    player.equipByName(chestplateName);
                }
                if (!leggingName.isEmpty()) {
                    player.equipByName(leggingName);
                }
                if (!bootName.isEmpty()) {
                    player.equipByName(bootName);
                }
                
                // 确保属性同步到组件
                player.syncAttributesToComponent();
            } else {
                // 没有存档时，设置默认血量
                int defaultMaxHealth = (int) (100 * Math.pow(1.1, player.getCombatLevel() - 1));
                player.setMaxHealth(defaultMaxHealth);
                if (player.getHealthComponent() != null) {
                    player.getHealthComponent().setHealth(defaultMaxHealth);
                }
            }
        }
        // 没有存档时，保持resetStatic后的初始状态
        initUI();
        // 再次隐藏player实体，彻底防止闪现
        if (playerEntity != null) {
            playerEntity.getViewComponent().setVisible(false);
        }
    }

    protected void initUI() {
        // 进入GameScene时只停止MenuMusic，不影响HomeMusic
        comgame.scenes.MusicManager.stopMenuMusic();
        // 初始化根容器
        sceneRoot = new StackPane();
        sceneRoot.setPrefSize(800, 600);
        sceneRoot.setStyle("-fx-background-color: transparent;");
        // 防止重复添加节点
        sceneRoot.getChildren().clear();

        // 添加背景图片
        Image backgroundImg;
        try {
            backgroundImg = new Image(Objects.requireNonNull(
                    getClass().getResourceAsStream("/assets/textures/gamescenebackground.png")));
        } catch (Exception e) {
            System.err.println("背景图片加载异常: " + e.getMessage());
            backgroundImg = null;
        }

        if (backgroundImg != null) {
            ImageView background = new ImageView(backgroundImg);
            background.setFitWidth(1000);
            background.setFitHeight(750);
            sceneRoot.getChildren().add(background);
        }

        // 主界面切换时不再stopAll，只在未播放时播放HomeMusic
        if (comgame.scenes.MusicManager.homeMusic == null)
            comgame.scenes.MusicManager.homeMusic = FXGL.getAssetLoader().loadMusic("HomeMusic.mp4");
        FXGL.getAudioPlayer().loopMusic(comgame.scenes.MusicManager.homeMusic);
        comgame.scenes.MusicManager.isHomeMusicPlaying = true;

        // 玩家信息按钮（左上角）
        Button playerInfoBtn = createSingleImageButton(
                "/assets/textures/player.png",
                "玩家信息",
               4
        );
        StackPane.setAlignment(playerInfoBtn, Pos.TOP_LEFT);
        StackPane.setMargin(playerInfoBtn, new javafx.geometry.Insets(10, 0, 0, 10));
        playerInfoBtn.setOnMouseClicked(e -> {
            togglePlayerInfoPanel();
        });
        // sceneRoot.getChildren().add(playerInfoBtn); // 删除这行，避免重复添加

        // 加载按钮音效
        AudioPlayer audioPlayer = FXGL.getAudioPlayer();
        Sound clickSound = FXGL.getAssetLoader().loadSound("drop.wav");

        // 创建图片按钮 - 菜地1 (缩小20%)
        Button firmBtn1 = createSingleImageButton(
                "/assets/textures/farmland2.png",
                "菜地1",
                0.3 // 缩小比例
        );

        // 创建图片按钮 - 菜地2 (缩小20%)
        Button firmBtn2 = createSingleImageButton(
                "/assets/textures/fishpool.png",
                "菜地2",
                0.45  // 缩小比例
        );

        // 创建图片按钮 - 商店
        Button shopBtn = createSingleImageButton(
                "/assets/textures/storehouse.png",
                "商店",
                2.0  // 原始大小
        );

        // 创建图片按钮 - 房子
        Button homeBtn = createSingleImageButton(
                "/assets/textures/house.png",
                "房子",
                1.0  // 原始大小
        );

        // 创建图片按钮 - 传送门
        Button portalBtn = createSingleImageButton(
                "/assets/textures/portal.png",
                "传送门",
                1.0  // 原始大小
        );

        // 设置商店按钮位置 (中上位置)
        StackPane.setAlignment(shopBtn, Pos.TOP_CENTER);
        StackPane.setMargin(shopBtn, new javafx.geometry.Insets(50, 0, 0, 0));

        // 设置Y轴基准线和X轴偏移量
        double shopY = 350; // 商店Y轴基准线
        double offsetX = 200; // X轴偏移量
        double verticalGap = 200; // 垂直间距

        // 设置房子按钮位置 (在菜地1上方)
        StackPane.setAlignment(homeBtn, Pos.TOP_LEFT);
        StackPane.setMargin(homeBtn, new javafx.geometry.Insets(shopY - verticalGap, 0, 0, offsetX));

        // 设置菜地1按钮位置 (在房子下方)
        StackPane.setAlignment(firmBtn1, Pos.TOP_LEFT);
        StackPane.setMargin(firmBtn1, new javafx.geometry.Insets(shopY, 0, 0, offsetX));

        // 设置传送门按钮位置 (在菜地2上方)
        StackPane.setAlignment(portalBtn, Pos.TOP_RIGHT);
        StackPane.setMargin(portalBtn, new javafx.geometry.Insets(shopY - verticalGap, offsetX, 0, 0));

        // 设置菜地2按钮位置 (在传送门下方)
        StackPane.setAlignment(firmBtn2, Pos.TOP_RIGHT);
        StackPane.setMargin(firmBtn2, new javafx.geometry.Insets(shopY, offsetX, 0, 0));

        // 绑定按钮点击事件
        firmBtn1.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);
            openFarmScene();
        });

        firmBtn2.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);
            FishpoolScene();
        });

        shopBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);
            StorehouseScene();
        });

        homeBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);
            HomeScene();
        });

        portalBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);
            MapScene();
        });


        // 将按钮添加到场景
        sceneRoot.getChildren().addAll(shopBtn, homeBtn, firmBtn1, portalBtn, firmBtn2);
        // 最后添加玩家信息按钮，保证在最上层可点击
        sceneRoot.getChildren().add(playerInfoBtn);
        // 将根容器添加到FXGL场景的内容容器中
        getContentRoot().getChildren().add(sceneRoot);

    }

    // 创建单张图片按钮的辅助方法 (增加了缩放参数)
    private Button createSingleImageButton(String imagePath, String text, double scale) {
        if (!imagePath.startsWith("/")) {
            imagePath = "/" + imagePath;
        }

        // 通过URL加载（可抛出详细异常）
        URL imageUrl = getClass().getResource(imagePath);
        if (imageUrl == null) {
            throw new RuntimeException("资源未找到: " + imagePath);
        }

        // 计算目标尺寸
        Image rawImage = new Image(imageUrl.toExternalForm());
        double targetWidth = rawImage.getWidth() * scale;
        double targetHeight = rawImage.getHeight() * scale;

        // ✅ 高质量预缩放
        Image buttonImage = new Image(
                imageUrl.toExternalForm(),
                targetWidth, targetHeight, true, true, true
        );

        ImageView imageView = new ImageView(buttonImage);
        Button button = new Button();
        button.setGraphic(imageView);

        // 设置按钮尺寸
        button.setPrefSize(imageView.getFitWidth(), imageView.getFitHeight());

        // 移除默认样式
        button.setStyle("-fx-background-color: transparent; -fx-border-color: transparent;");

        // 创建阴影效果（悬停时使用）
        DropShadow shadow = new DropShadow();
        shadow.setColor(Color.WHITE);
        shadow.setRadius(10);

        // 设置按钮状态变化事件
        button.setOnMouseEntered(e -> {
            button.setEffect(shadow);        // 添加阴影
            button.setOpacity(0.9);          // 轻微透明
        });

        button.setOnMouseExited(e -> {
            button.setEffect(null);          // 移除阴影
            button.setOpacity(1.0);          // 恢复不透明
        });

        button.setOnMousePressed(e -> {
            button.setOpacity(0.8);          // 点击时更透明
            button.setScaleX(0.98);          // 轻微缩小
            button.setScaleY(0.98);
        });

        button.setOnMouseReleased(e -> {
            button.setOpacity(0.9);          // 恢复悬停状态
            button.setScaleX(1.0);           // 恢复大小
            button.setScaleY(1.0);
        });

        return button;
    }
    public void openFarmScene() {
        // 确保隐藏玩家实体
        if (playerEntity != null) {
            playerEntity.getViewComponent().setVisible(false);
        }
        FXGL.getGameScene().clearUINodes();
        PlantScene plantScene = new PlantScene();
        FXGL.getGameScene().addUINode(plantScene.getContentRoot());

        // 可选：添加切换动画
        FadeTransition fadeIn = new FadeTransition(Duration.seconds(0.5), plantScene.getContentRoot());
        fadeIn.setFromValue(0);
        fadeIn.setToValue(1);
        fadeIn.play();
    }

    public void StorehouseScene() {
        // 确保隐藏玩家实体
        if (playerEntity != null) {
            playerEntity.getViewComponent().setVisible(false);
        }
        FXGL.getGameScene().clearUINodes();
        StorehouseScene storehouseScene = new StorehouseScene();
        FXGL.getGameScene().addUINode(storehouseScene.getContentRoot());

        // 可选：添加切换动画
        FadeTransition fadeIn = new FadeTransition(Duration.seconds(0.5), storehouseScene.getContentRoot());
        fadeIn.setFromValue(0);
        fadeIn.setToValue(1);
        fadeIn.play();
    }

    public void FishpoolScene() {
        // 确保隐藏玩家实体
        if (playerEntity != null) {
            playerEntity.getViewComponent().setVisible(false);
        }
        FXGL.getGameScene().clearUINodes();
        FishpoolScene fishpoolScene = new FishpoolScene();
        FXGL.getGameScene().addUINode(fishpoolScene.getContentRoot());

        // 可选：添加切换动画
        FadeTransition fadeIn = new FadeTransition(Duration.seconds(0.5), fishpoolScene.getContentRoot());
        fadeIn.setFromValue(0);
        fadeIn.setToValue(1);
        fadeIn.play();
    }

    public void MapScene() {
        // 确保隐藏玩家实体
        if (playerEntity != null) {
            playerEntity.getViewComponent().setVisible(false);
        }
        FXGL.getGameScene().clearUINodes();
        MapScene mapScene = new MapScene();
        FXGL.getGameScene().addUINode(mapScene.getContentRoot());

        // 可选：添加切换动画
        FadeTransition fadeIn = new FadeTransition(Duration.seconds(0.5), mapScene.getContentRoot());
        fadeIn.setFromValue(0);
        fadeIn.setToValue(1);
        fadeIn.play();
    }

    public void HomeScene() {
        // 确保隐藏玩家实体
        if (playerEntity != null) {
            playerEntity.getViewComponent().setVisible(false);
        }
        FXGL.getGameScene().clearUINodes();
        HomeScene homeScene = new HomeScene();
        FXGL.getGameScene().addUINode(homeScene.getContentRoot());

        // 可选：添加切换动画
        FadeTransition fadeIn = new FadeTransition(Duration.seconds(0.5), homeScene.getContentRoot());
        fadeIn.setFromValue(0);
        fadeIn.setToValue(1);
        fadeIn.play();
    }


    // 切换玩家属性面板显示/隐藏
    private void togglePlayerInfoPanel() {
        if (player == null) {
            FXGL.showMessage("玩家数据未初始化，无法显示属性面板！");
            return;
        }
        
        // 如果面板已显示，则隐藏
        if (playerInfoPanel != null && sceneRoot.getChildren().contains(playerInfoPanel)) {
            sceneRoot.getChildren().remove(playerInfoPanel);
            if (infoPanelTimeline != null) infoPanelTimeline.stop();
            return;
        }
        
        // 强制同步玩家数据，确保显示最新值
        player.syncAttributesToComponent();
        
        // 每次显示时重新创建面板以确保数据最新
        playerInfoPanel = createPlayerInfoPanel();
        sceneRoot.getChildren().add(playerInfoPanel);
        
        // 启动定时刷新所有属性
        infoPanelTimeline = new javafx.animation.Timeline(
            new javafx.animation.KeyFrame(javafx.util.Duration.seconds(0.1), e -> {
                if (player != null) {
                    updatePlayerInfoPanel();
                }
            })
        );
        infoPanelTimeline.setCycleCount(javafx.animation.Animation.INDEFINITE);
        infoPanelTimeline.play();
    }

    // 创建玩家属性面板
    private VBox createPlayerInfoPanel() {
        VBox panel = new VBox(16);
        panel.setStyle("-fx-background-color: rgba(255,255,255,0.96); -fx-border-color: #4A90E2; -fx-border-width: 2.5; -fx-border-radius: 22; -fx-background-radius: 22; -fx-padding: 28; -fx-effect: dropshadow(gaussian, #4A90E2, 24, 0.28, 0, 6);");
        double panelWidth = 420;
        double panelHeight = 450;
        panel.setPrefWidth(panelWidth);
        panel.setPrefHeight(panelHeight);
        panel.setMaxWidth(panelWidth);
        panel.setMaxHeight(panelHeight);
        panel.setMinWidth(panelWidth);
        panel.setMinHeight(panelHeight);
        panel.setAlignment(Pos.TOP_CENTER);
        StackPane.setAlignment(panel, Pos.CENTER);
        StackPane.setMargin(panel, javafx.geometry.Insets.EMPTY);
        // 标题
        javafx.scene.control.Label title = new javafx.scene.control.Label("玩家属性");
        title.setStyle("-fx-font-size: 26px; -fx-font-weight: bold; -fx-text-fill: #2D3E50;");
        // 分隔线
        javafx.scene.shape.Line line = new javafx.scene.shape.Line(0, 0, panelWidth - 56, 0);
        line.setStyle("-fx-stroke: #4A90E2; -fx-stroke-width: 2.2;");
        // 属性内容用GridPane
        javafx.scene.layout.GridPane grid = new javafx.scene.layout.GridPane();
        grid.setVgap(16);
        grid.setHgap(18);
        grid.setPrefWidth(panelWidth - 56);
        grid.setAlignment(Pos.CENTER);
        String[] names = {"攻击", "防御", "暴击率", "速度", "金钱", "血量", "种植等级", "战斗等级"};
        String[] values = {
            String.format("%.1f", player.getAttack()),
            String.format("%.1f", player.getDefense()),
            String.format("%.1f%%", player.getCritRate() * 100),
            String.format("%.1f", player.getSpeed()),
            String.format("%d", player.getMoney()),
            String.format("%d/%d", player.getHealth(), player.getMaxHealth()),
            String.format("%d", player.getFarmingLevel()),
           String.format("%d (%d/%d)", player.getCombatLevel(), player.getCombatExp(), player.getCombatExpRequired())
        };
        javafx.scene.control.Label[] valueLabels = new javafx.scene.control.Label[names.length];
        for (int i = 0; i < names.length; i++) {
            javafx.scene.control.Label nameLabel = new javafx.scene.control.Label(names[i] + ":");
            nameLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-text-fill: #34495E; -fx-alignment: CENTER_LEFT;");
            javafx.scene.control.Label valueLabel = new javafx.scene.control.Label(values[i]);
            valueLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-text-fill: #34495E; -fx-alignment: CENTER_RIGHT;");
            grid.add(nameLabel, 0, i);
            grid.add(valueLabel, 1, i);
            valueLabels[i] = valueLabel;
            if (i == 4) moneyLabel = valueLabel; // 修正为金钱在第5行
            javafx.scene.layout.ColumnConstraints left = new javafx.scene.layout.ColumnConstraints();
            left.setHalignment(javafx.geometry.HPos.LEFT);
            left.setPercentWidth(60);
            javafx.scene.layout.ColumnConstraints right = new javafx.scene.layout.ColumnConstraints();
            right.setHalignment(javafx.geometry.HPos.RIGHT);
            right.setPercentWidth(40);
            if (grid.getColumnConstraints().isEmpty()) {
                grid.getColumnConstraints().addAll(left, right);
            }
        }
        panel.getChildren().setAll(title, line, grid);
        // 点击面板外关闭
        panel.setOnMouseClicked(e -> e.consume()); // 防止冒泡
        sceneRoot.setOnMouseClicked(e -> {
            if (playerInfoPanel != null && sceneRoot.getChildren().contains(playerInfoPanel)) {
                sceneRoot.getChildren().remove(playerInfoPanel);
                if (infoPanelTimeline != null) infoPanelTimeline.stop();
            }
            sceneRoot.setOnMouseClicked(null); // 只监听一次
        });
        return panel;
    }

    // 更新玩家属性面板
    private void updatePlayerInfoPanel() {
        if (playerInfoPanel == null || player == null) return;
        
        // 强制同步玩家数据，确保显示最新值
        
        // 获取面板中的GridPane
        javafx.scene.layout.GridPane grid = (javafx.scene.layout.GridPane) playerInfoPanel.getChildren().get(2);
        
        // 更新所有属性值
        String[] values = {
            String.format("%.1f", player.getAttack()),
            String.format("%.1f", player.getDefense()),
            String.format("%.1f%%", player.getCritRate() * 100),
            String.format("%.1f", player.getSpeed()),
            String.format("%d", player.getMoney()),
            String.format("%d/%d", player.getHealth(), player.getMaxHealth()),
            String.format("%d", player.getFarmingLevel()), String.format("%d (%d/%d)", player.getCombatLevel(), player.getCombatExp(), player.getCombatExpRequired())
        };
        
        // 更新GridPane中的值标签
        for (int i = 0; i < values.length; i++) {
            javafx.scene.control.Label valueLabel = (javafx.scene.control.Label) grid.getChildren().get(i * 2 + 1);
            valueLabel.setText(values[i]);
        }
    }

    public static void showPlayer() {
        if (playerEntity != null && !playerEntity.getViewComponent().isVisible()) {
            playerEntity.getViewComponent().setVisible(true);
        }
    }
    public static void hidePlayer() {
        if (playerEntity != null && playerEntity.getViewComponent().isVisible()) {
            playerEntity.getViewComponent().setVisible(false);
        }
    }

    public static void removePlayerEntityFromWorld() {
        if (playerEntity != null && playerEntity.isActive()) {
            playerEntity.removeFromWorld();
        }
    }

    // 静态方法：重新创建玩家实体
    public static void recreatePlayerEntity() {
        // 如果玩家实体存在但已不活跃，先移除它
        if (playerEntity != null && !playerEntity.isActive()) {
            try {
                playerEntity.removeFromWorld();
            } catch (Exception e) {
                System.out.println("移除旧玩家实体时出错: " + e.getMessage());
            }
        }
        
        // 重新创建玩家实体
        System.out.println("重新创建玩家实体");
        playerEntity = FXGL.spawn("player", 200, 400);
        player = new Player(playerEntity);
        
        // 重新加载玩家数据
        org.json.JSONObject saveObj = comgame.scenes.DataSaveManager.getLastPlayerSaveObj();
        if (saveObj != null) {
            player.getMoneyComponent().setAmount(saveObj.getInt("money"));
            player.getSkillComponent().setCombatLevel(saveObj.getInt("combatLevel"));
            player.getSkillComponent().setCombatExp(saveObj.getInt("combatExp"));
            player.getSkillComponent().setFarming(saveObj.getInt("farmingLevel"));
            
            // 设置血量
            int maxHealth = saveObj.getInt("maxHealth");
            player.setMaxHealth(maxHealth);
            if (player.getHealthComponent() != null) {
                player.getHealthComponent().setHealth(maxHealth);
            }
            
            // 加载装备
            String swordName = saveObj.optString("sword", "");
            String helmetName = saveObj.optString("helmet", "");
            String chestplateName = saveObj.optString("chestplate", "");
            String leggingName = saveObj.optString("legging", "");
            String bootName = saveObj.optString("boot", "");
            
            if (!swordName.isEmpty()) {
                player.equipByName(swordName);
            }
            if (!helmetName.isEmpty()) {
                player.equipByName(helmetName);
            }
            if (!chestplateName.isEmpty()) {
                player.equipByName(chestplateName);
            }
            if (!leggingName.isEmpty()) {
                player.equipByName(leggingName);
            }
            if (!bootName.isEmpty()) {
                player.equipByName(bootName);
            }
            
            // 确保属性同步到组件
            player.syncAttributesToComponent();
        }
        
        // 确保玩家实体可见
        if (playerEntity != null) {
            playerEntity.getViewComponent().setVisible(true);
        }
    }

    // 静态方法：强制更新属性面板
    public static void forceUpdatePlayerInfoPanel() {
        if (player != null) {
            // 同步组件数据
            player.syncAttributesToComponent();
            
            // 强制刷新属性面板 - 通过重新加载玩家数据来确保数据同步
            
            // 重新同步属性组件 - 只有在playerEntity存在且活跃时才操作
            if (playerEntity != null && playerEntity.isActive()) {
                try {
                    AttributeComponent attrComp = playerEntity.getComponent(AttributeComponent.class);
                    if (attrComp != null) {
                        attrComp.setAttack(player.getAttack());
                        attrComp.setDefense(player.getDefense());
                        attrComp.setCritRate(player.getCritRate());
                        attrComp.setSpeed(player.getSpeed());
                    }
                } catch (IllegalArgumentException e) {
                    // 如果组件不存在，说明玩家实体可能已被删除，需要重新创建
                    System.out.println("玩家实体组件不存在，重新创建玩家实体");
                    recreatePlayerEntity();
                }
            } else {
                // 如果玩家实体不存在或不活跃，重新创建
                System.out.println("玩家实体不存在或不活跃，重新创建玩家实体");
                recreatePlayerEntity();
            }
        }
    }

    public StackPane getSceneRoot() {
        return sceneRoot;
    }

    // 存档方法
    private void saveGame() {
        comgame.scenes.DataSaveManager.saveAll();
    }
    // 读档方法
    private void loadGame() {
        comgame.scenes.DataSaveManager.loadAll();
    }
}